<?php
// +----------------------------------------------------------------------
// | duoduojie app system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 duoduojie app All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace Ddj;
/**
 * 京东联盟接口
 * @author zqs
 */
include env('extend_path').'/jd/JdSdk.php';
class Jd
{
    public $options;
    //public $server_url = 'https://api.jd.com/routerjson';
    /**
     * 初始化
     */
    public function __construct($options=[])
    {
        //公共参数,可被覆盖
        $db_config = get_db_config(true);
        $this->options['appkey'] = $db_config['tk_cfg']['jd']['appkey'] ?? '';
        $this->options['appsecret'] = $db_config['tk_cfg']['jd']['appsecret'] ?? '';
//        $this->options['accesstoken'] = $db_config['tk_cfg']['jd']['accesstoken'] ?? '';
        $this->options['unionid'] = $db_config['tk_cfg']['jd']['unionid'] ?? '';
        $this->options['pid'] = $db_config['tk_cfg']['jd']['pid'] ?? '';
        $this->options['key'] = $db_config['tk_cfg']['jd']['key'] ?? '';
        
        $this->options['big_appkey'] = $db_config['tk_cfg']['jd']['big_appkey'] ?? '';
        $this->options['big_appsecret'] = $db_config['tk_cfg']['jd']['big_appsecret'] ?? '';
        $this->options['big_accesstoken'] = $db_config['tk_cfg']['jd']['big_accesstoken'] ?? '';
        if ($options){
            $this->options = array_merge($this->options,$options);
        }
    }
    /**
     * 	优惠券商品查询【申请】,借用
     */
    public function query_coupon_goods()
    {
        $c = new \JdClient();
        $c->appKey = $this->options['big_appkey'];
        $c->appSecret = $this->options['big_appsecret'];
        $c->accessToken = $this->options['big_accesstoken'];
        //$c->serverUrl = $this->server_url;
        $req = new \UnionSearchQueryCouponGoodsRequest();
        //skuId集合，长度最大30，可为空。如果传值，忽略其他查询条件。 
        $req->setSkuIdList($this->options['skuIdList'] ?? "");
        //页码，默认1 
        $req->setPageIndex($this->options['pageIndex'] ?? 1);
        //单页数最大30，默认20
        $req->setPageSize($this->options['pageSize'] ?? 20); 
        //三级类目
        $req->setCid3($this->options['cid3'] ?? "");
        //商品关键词
        $req->setGoodsKeyword($this->options['q'] ?? "");
        //商品价格下限 
        $req->setPriceFrom($this->options['priceFrom'] ?? "");
        //商品价格上限
        $req->setPriceTo($this->options['priceTo'] ?? "");
        
        $resp = $c->execute($req, $c->accessToken);
        $resp = json_decode(json_encode($resp),true);
        $resp['query_coupon_goods_result'] = json_decode($resp['query_coupon_goods_result'],true);
        return $resp;
    }
    /**
     * 优惠券,商品二合一转接API-通过unionId获取推广链接【申请】 ,借用
     * 京东跟单用推广位id,不是pid
     */
    public function get_code_buy_uniodid($item_id,$url)
    {
        $url = trim($url);
        $c = new \JdClient();
        $c->appKey = $this->options['big_appkey'];
        $c->appSecret = $this->options['big_appsecret'];
        $c->accessToken = $this->options['big_accesstoken'];
        //缓存处理
        $cache_url = cache('jd_url_'.$url.'_'.$item_id.'_'.$this->options['pid'].'_'.$this->options['unionid']);
        if ($cache_url){
            return $cache_url;
        }
        $req = new \ServicePromotionCouponGetCodeByUnionIdRequest();
        $req->setCouponUrl($url); 
        $req->setMaterialIds($item_id); 
        $req->setUnionId($this->options['unionid']); 
        $req->setPositionId($this->options['pid']); //推广位id非pid
        $req->setPid("");//不知道是什么玩意
        
        $resp = $c->execute($req, $c->accessToken);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['code']=='0'){
            //获取成功并不一定真的生成了
            $re = json_decode($resp['getcodebyunionid_result'],true);
            $re_url = $re['urlList'][$url.','.$item_id] ?? false;
            if ($re_url){
                cache('jd_url_'.$url.'_'.$item_id.'_'.$this->options['pid'].'_'.$this->options['unionid'],$re_url);
                return $re_url;
            }
        }
        return false;
    }
    /**
     * 批量创建推广位【申请】,借用
     */
    public function create_promotion_site_batch($uid)
    {
        $c = new \JdClient();
        $c->appKey = $this->options['big_appkey'];
        $c->appSecret = $this->options['big_appsecret'];
        $c->accessToken = $this->options['big_accesstoken'];
        
        $req = new \ServicePromotionCreatePromotionSiteBatchRequest();
        
        $req->setUnionId($this->options['unionid']); 
        $req->setKey($this->options['key']); 
        $req->setUnionType(1); 
        $req->setType(4); 
        $req->setSiteId("");
        $space_name = $this->options['space_name'] ?? 'u_'.$uid;
        $req->setSpaceName($space_name);
        
        $resp = $c->execute($req, $c->accessToken);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['jingdong_service_promotion_createPromotionSiteBatch_responce']['code']==0){//响应成功
            $re = json_decode($resp['create_promotion_site_result'],true);
            if ($re['code']==200){//真实成功
                return $re['data']['resultList'][$space_name];
            }
        }
        return false;
    }
    /**
     * 京东获取商品详情
     */
    public function item_info($item_id)
    {
        $c = new \JdClient();
        $c->appKey = $this->options['big_appkey'];
        $c->appSecret = $this->options['big_appsecret'];
        $c->accessToken = $this->options['big_accesstoken'];
        
        $req = new \ServicePromotionGoodsInfoRequest();
        $req->setSkuIds($item_id);
        $resp = $c->execute($req, $c->accessToken);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['code']==0){
            $resp['getpromotioninfo_result'] = json_decode($resp['getpromotioninfo_result'],true);
            if ($resp['getpromotioninfo_result']['sucessed']){
                return $resp;
            }
        }
        return false;
    }
    /**
     * 优惠券详情
     */
    public function coupon_info($coupon_url)
    {
        $c = new \JdClient();
        $c->appKey = $this->options['big_appkey'];
        $c->appSecret = $this->options['big_appsecret'];
        $c->accessToken = $this->options['big_accesstoken'];
        
        $req = new \ServicePromotionCouponGetInfoRequest();
        $req->setCouponUrl($coupon_url);
        $resp = $c->execute($req, $c->accessToken);
        $resp = json_decode(json_encode($resp),true);
        if ($resp['code']==0){
            $resp['getinfo_result'] = json_decode($resp['getinfo_result'],true);
            if ($resp['getinfo_result']['resultCode']=='0'){
                return $resp;
            }
        }
        return false;
    }
    
    /**
     * 京推推 -商品列表API
     */
    public function jtt_goods_list()
    {
        $url = 'http://japi.jingtuitui.com/api/get_goods_list';
        $appid = '1811050058417802';
        $appkey = 'e9efcc2f50ec76c4262ddf34bdfeb1c6';
        $param = [
            'appid' => $appid,
            'appkey' => $appkey,
        ];
        if (isset($this->options['page'])) $param['page'] = $this->options['page'];
        if (isset($this->options['num'])) $param['num'] = $this->options['num'];
        if (isset($this->options['type'])) $param['type'] = $this->options['type'];
        if (isset($this->options['rank'])) $param['type'] = $this->options['rank'];
        //缓存处理
        $cache_name = arr2str($param,'_');
        $cache_data = cache($cache_name);
        if ($cache_data){
            return $cache_data;
        }
        
        $re = http_post($url, $param);
        $re = json_decode($re,true);
        if ($re['return']==0){
            $data =  $re['result']['data'];
            //内容转换
            $new_data = [];
            foreach ($data as $k=>$v){
                $temp = [
                    'tjp' => 'j',
                    'search' => 0,
                    'title' => $v['goods_name'],
                    'short_title' => $v['goods_name'],
                    'item_id' => $v['goods_id'],
                    'is_tmall' => 2,
                    'is_tmall_text' => '京东',
                    'rate' => $v['commission'],
                    'quan_price' => $v['discount_price'],
                    'price' => $v['goods_price'],
                    'price_after_quan' => $v['coupon_price'],
                    'sales' => 0,
                    'shop_title' => '',
                    'pic' => $v['goods_img'],
                    'url' => $v['discount_link'],//券链接
                    'coupon_start_time' => date('Y-m-d',substr($v['discount_start'], 0,-3)),
                    'coupon_end_time' => date('Y-m-d',substr($v['discount_end'], 0,-3)),
                    'coupon_total_count' => 0,//京东无此参数
                    'coupon_remain_count' => 0,
                ];
                $new_data[] = $temp;
            }
            cache($cache_name,$new_data,3600);//缓存一小时
            return $new_data;
        }
        return false;
    }
    /**
     * 导订单
     */
    public function import_order($start_time)
    {
        $c = new \JdClientOrder();
        $c->appKey = $this->options['appkey'];
        $c->appSecret = $this->options['appsecret'];
//        $c->accessToken = $this->options['accesstoken'];
        
        $req = new \UnionServiceQueryOrderListRequest();
        
//        $req->setUnionId($this->options['unionid']);
        $req->setTime($start_time);
        $req->setPageIndex($this->options['page_no']??1);
        $req->setPageSize($this->options['page_size']??100);
        $req->setType(1);

        $resp = $c->execute($req);
        $resp = json_decode(json_encode($resp),true);
        $resp['result'] = json_decode($resp['result'],true);
        return $resp['result'];
    }

    

    
    
    
    
}